package com.lxx.jmb2c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxx.jmb2c.entity.Category;
import com.lxx.jmb2c.entity.Goods;
import com.lxx.jmb2c.exceptions.BusinessException;
import com.lxx.jmb2c.mapper.CategoryMapper;
import com.lxx.jmb2c.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxx.jmb2c.service.GoodsService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 产品分类表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-10
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Lazy
    @Resource
    private GoodsService goodsService;

    @Override
    public IPage<Category> getPage(Long current, Long pageSize, String name) {
        //pageInfo描述的是页面的规格信息，当前第几页，一页多少条数据
        IPage<Category> pageInfo=new Page<>(current,pageSize);
        //构建查询条件，相当于sql中的where
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //StringUtils.hasText(name)判断name是否为空，不为空则构建查询条件
        wrapper.like(StringUtils.hasText(name),Category::getName, name);

        IPage<Category> page = this.page(pageInfo, wrapper);
        return page;
    }

    @Override
    public void enable(Long id) {
        Category category = this.getById(id);
        if(category==null){
            throw new BusinessException("分类不存在");
        }
        category.setVisibility(!category.getVisibility());
        this.updateById(category);
    }

    @Override
    public void deleteBatchByIds(List<Long> ids) {
        //当ids里面有任何一个分类是被使用的，则不允许删除
        for (Long categoryId : ids) {
            LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Goods::getCategoryId, categoryId);
            long count = this.goodsService.count(wrapper);
            if(count>0){
                Category category = this.getById(categoryId);
                throw new BusinessException("分类:"+category.getName()+"被使用，不允许删除");
            }
        }
        //代码能执行到这里，说明列表中分类没有被使用，可以删除
        this.removeBatchByIds(ids);
    }
}
